package com.heima.search.service.impl;

import com.heima.common.search.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.SearchService;
import com.heima.search.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;


import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticSearchTemplate  elasticSearchTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    //新增搜索记录
    @Override
    public void insert(String keyword, Integer userId) {
        //参数判空
        if (StringUtils.isEmpty(keyword) && userId == null){
            log.warn("参数不合法");
            return;
        }
        //根据参数，查看历史记录中是否有重复查询
        Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        if (apUserSearch != null){
            //有，更新创建时间
            apUserSearch.setCreatedTime(new Date());
        }else{
            //没有，就插入  插入的话可以判断一下有没有超过10个
            apUserSearch = new ApUserSearch();
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setKeyword(keyword);
            apUserSearch.setUserId(userId);
        }
        mongoTemplate.save(apUserSearch);

    }

    //删除历史记录
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Date minBehotTime = dto.getMinBehotTime();
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        String searchWords = dto.getSearchWords();

        //构建查询条件
        //关键词匹配
        QueryStringQueryBuilder stringQueryBuilder = elasticSearchTemplate.getStringQueryBuilder(searchWords, Operator.OR, "title", "content");
        //时间匹配.
        Map<String, Object> rangeCondition = new HashMap<>(1);
        rangeCondition.put("lt",minBehotTime.getTime());
        RangeQueryBuilder rangeBuilder = elasticSearchTemplate.getRangeBuilder("publishTime", rangeCondition);
        //bool
        Map<String, AbstractQueryBuilder> boolCondition = new HashMap<>(2);
        boolCondition.put("must",stringQueryBuilder);
        boolCondition.put("filer",rangeBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(boolCondition);
        //高亮
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title", "<font style='color: red; font-size: inherit;'>", "</font>");

        //构建查询条件
        SearchResponse searchResponse = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);

        //解析响应结果
        SearchHits hits = searchResponse.getHits();
        SearchHit[] resultHits = hits.getHits();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit resultHit : resultHits) {
            Map<String, Object> sourceAsMap = resultHit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = resultHit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                Text[] titles = highlightFields.get("title").getFragments();
                String join = StringUtils.join(titles, ",");
                sourceAsMap.put("h_title",join);
            }else{
                sourceAsMap.put("h_title",sourceAsMap.get("title"));
            }
            resultList.add(sourceAsMap);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            log.warn("查询文章------用户信息不存在");
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();

        //将搜索的内容保存到mangodb的搜索历史当中
        insert(dto.getSearchWords(), userId);

        return ResponseResult.okResult(resultList);
    }


}
